// pages/editCard.js
let app = getApp();
let util = require("../../utils/util");
let common = require("../../common/common");

// 必填/选 项
const formRequiredMap = {
    name: "姓名",
    phone: "手机号",
    address_detail: "详细地址",
    gender: "性别",
    introduce: "个人简介",
};

// 非必填项
const formNotRequireArr = [
    "company", "position", "wechat",
];

Page({

    /**
   * 页面的初始数据
   */
    data: {
        // <- 必填
        avatarUrl: "", // 头像
        genderList: [
            {
                name: "1", value: "男", checked: "true",
            }, {
                name: "2", value: "女",
            }
        ],
        nickName: "", // 昵称
        name: "", // 名字
        phone: "", // 电话
        industryList: common.industryList, // 行业
        index: 0,
        // -> 

        inputNameList: [
            ["公司", "company"], ["职务", "position"], ["微信", "wechat"],
        ],

        inputNameValue: [], // company, position, wechat 的值

        addressDetail: "",
        address: ["", "", ""], // 地址

        introduce: "", // 个人简介

        latitude: wx.getStorageSync("latitude"),
        longitude: wx.getStorageSync("longitude"),
        addNewIconUrl: "../../image/add.png",

        limitCount: 3, // 图片限制3张

        business: [{ name: "", intro: "", showImg: [] }], // 填写业务整个组件, length表示当前的组件个数; showImg: 图片url array

        businessName: "businessName",
        businessIntro: "businessIntro",

        tip: "", // 错误信息提示
        isChecked: false,
        imageDone: false, // 图片已拿到
    },
    bindIndustryPickerChange: function (e) {
        console.log("picker发送选择改变，携带值为", e.detail.value);
        this.setData({
            index: e.detail.value
        });
    },


    //定时器提示框3秒消失  
    onTipFadeOut() {
        let fadeOutTimeout = setTimeout(() => {
            this.setData({ tip: "" });
            clearTimeout(fadeOutTimeout);
        }, 3000);
    },

    setTipMsg: function (that, tipMsg) {
        this.setData({
            tip: "请" + tipMsg,
        });
        this.onTipFadeOut();
    },

    formSubmit: function (e) {
        let result = e.detail.value;
        let that = this;
        let resultItemArr = Object.keys(formRequiredMap);

        // 校验 必填/选
        for (let v of resultItemArr) {
            if (result[v].length === 0) {
                if (v === "gender") {
                    // this.setTipMsg(that, "选择" + formRequiredMap[v] + "!");
                    wx.showToast({
                        title: "请选择" + formRequiredMap[v] + "!",
                        image: "../../image/warn.png",
                    });
                    return;
                } else {
                    // this.setTipMsg(that, "填写" + formRequiredMap[v] + "！");
                    wx.showToast({
                        title: "请选择" + formRequiredMap[v] + "!",
                        image: "../../image/warn.png",
                    });
                    return;
                }
            }
        }

        // 校验格式
        let phoneRegExp = /^1[3|4|5|7|8][0-9]{9}$/;
        if (!phoneRegExp.test(result["phone"])) {
            wx.showToast({
                title: "手机号格式错了!",
                image: "../../image/warn.png",
            });
        }

        console.log("form发生了submit事件，携带数据为：", e.detail.value);


        let newAddress = result.address[0] === result.address[1] ? result.address[0] + result.address[2] : result.address.join("");
        console.log(" ____newAddress: ", newAddress);

        this.setData({
            address: newAddress,
            addressDetail: result.address_detail,
        });

        let openId = wx.getStorageSync("openId");
        console.log("  __openId: ", openId);

        let industry = common.industryList[that.data.index];

        let payload = {}; // request data

        payload.avatarUrl = that.data.avatarUrl;
        payload.openId = openId;
        payload.gender = Number(result.gender);
        payload.nickName = that.data.nickName;
        payload.name = result.name;
        payload.phone = result.phone;
        payload.industry = industry;
        payload.introduce = result.introduce;
        payload.business = that.data.business;

        for (let v of formNotRequireArr) {
            if (v.length !== "") {
                payload[v] = result[v];
            }
        }

        if (result.address_detail.length !== "") {
            payload["address.province"] = result.address[0];
            payload["address.city"] = result.address[1];
            payload["address.area"] = result.address[2];
            payload["address.detail"] = result.address_detail;
        }

        let list = wx.getStorageSync("list");
        console.log("  ______ payload: ", payload);

        if (list && list[0] && list[0].avatarUrl) {
            // 编辑 edit
            let id = list[0]._id;
            wx.request({
                url: common.domain + common.prefixUrl + "/" + id,
                method: "PUT",
                data: payload,
                success: res => {
                    console.log("  __PUT success res: ", res);
                    wx.showToast({
                        title: "名片修改成功!",
                        icon: "success",
                    });

                    setTimeout(function () {
                        wx.switchTab({
                            url: "../myCard/index",
                        });
                    }, 2000);
                }
            });
        } else {
            // 新增 add
            wx.request({
                url: common.domain + common.prefixUrl,
                method: "POST",
                data: payload,
                success: res => {
                    console.log("  __POST success res: ", res);
                    wx.showToast({
                        title: "名片新增成功!",
                        icon: "success",
                    });

                    setTimeout(function () {
                        wx.switchTab({
                            url: "../myCard/index",
                        });
                    }, 2000);
                }
            });
        }
    },

    bindAddressDetailChange: function (e) {
        console.log("  __*__e.detail.value: ", e.detail.value);
        let newAddressDetail = e.detail.value;

        if (!newAddressDetail) {
            this.setData({
                addressDetail: newAddressDetail
            });
        }

        let urlData = util.qqMapUrlDegree(this.data.address.join("") + newAddressDetail);
        console.log("  __urlData: ", urlData);

        let that = this;

        wx.request({
            url: urlData,
            success: res => {
                console.log("  __res__: ", res);
                console.log("  __res.data.result.location: ", res.data.result.location);

                let latitude = res.data.result.location.lat;
                let longitude = res.data.result.location.lng;
                console.log("latitude: ", latitude);
                console.log("longitude: ", longitude);
                that.setData({
                    latitude: latitude,
                    longitude: longitude,
                });
            }
        });
    },

    bindLocation: function (e) {

        let that = this;

        wx.chooseLocation({
            success: res => {
                console.log("  ____choose location chooseLocation res: ", res);
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    addressDetail: res.name,
                });

                let latitude = res.latitude;
                let longitude = res.longitude;
                let urlData = util.qqMapUrlCN(latitude, longitude);
                console.log("  __urlData: ", urlData);
                wx.request({
                    url: urlData,
                    success: res => {
                        console.log("  __res__: ", res);
                        console.log("  ___res.data.result.address_component: ", res.data.result.address_component);
                        let addressComponent = res.data.result.address_component;

                        that.setData({
                            latitude: latitude,
                            longitude: longitude,
                            address: [addressComponent.province, addressComponent.city, addressComponent.district],
                        });

                    }
                });

            }
        });



    },

    fullscreenMap: function () {
        wx.getLocation({
            type: "gcj02", //返回可以用于wx.openLocation的经纬度  
            success: function (res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                console.log("latitude: ", latitude);
                console.log("longitude: ", longitude);
                wx.openLocation({
                    latitude: latitude,
                    longitude: longitude,

                    scale: 28
                });
            },
            cancel: function (res) {
                alert("请允许获取您的地理位置！");
                wx.closeWindow();
            },
            fail: function (res) {
                alert("没有获得位置权限！");
                wx.closeWindow();
            }
        });
    },

    bindAddressPickerChange: function (e) {
        console.log(" ___e: ", e);
        console.log(" __e.detail.value: ", e.detail.value);
        console.log(" __this: ", this);
        this.setData({
            address: e.detail.value,
        });
    },

    chooseAvatarImg: function () {
        let that = this;
        wx.chooseImage({
            count: 1,
            success: res => {
                console.log(" __Avatar___res: ", res);

                this.setData({
                    avatarUrl: res.tempFilePaths[0],
                });
            }
        });
    },

    chooseImage: function (e) {
        console.log("in editCard chooseImage e: ", e);
        let that = this;
        let idx = e.currentTarget.dataset.index;
        wx.chooseImage({
            count: that.data.limitCount,
            success: function (res) {
                let newBusiness = that.data.business;
                newBusiness[idx].showImg = res.tempFilePaths;
                that.setData({
                    business: newBusiness
                });
            },
        });
    },

    previewImage: function (e) {
        let currentUrl = e.target.dataset.src; // 选中的图片url
        let idx = e.currentTarget.dataset.index; // business index

        wx.previewImage({
            current: currentUrl,
            urls: this.data.business[idx].showImg,
        });
    },

    clearUploadImg: function (e) {
        console.log("  ______ in editCard clearUploadImg e: ", e);
        let idx = e.currentTarget.dataset.index; // business index
        let imgIdx = e.currentTarget.dataset.imgidx; // showImg index
        // let path = e.target.dataset.imgurl;
        // let pos = 0;
        // for (let i = 0; i < list.length; i++) {
        //     if (list[i].path === path) {
        //         pos = i;
        //     }
        // }
        // let newImageList = this.data.imageList;
        // newImageList.splice(pos, 1);
        let newBusiness = this.data.business;
        newBusiness[idx].showImg.splice(imgIdx, 1);
        this.setData({
            business: newBusiness,
        });
    },

    // 业务名 business[idx].name
    businessNameBlur: function (e) {
        console.log("in editCard e: ", e);

        let idx = e.target.dataset.index; // business 中的 index
        let newBusiness = this.data.business;
        newBusiness[idx].name = e.detail.value;

        this.setData({
            business: newBusiness,
        });
    },

    // 业务介绍 business[idx].intro
    businessIntroBlur: function (e) {
        let idx = e.target.dataset.index; // business 中的 index
        let newBusiness = this.data.business;
        newBusiness[idx].intro = e.detail.value;

        this.setData({
            business: newBusiness,
        });
    },

    // 点击 增加业务
    bindAddBusiness: function () {
        let newbusiness = this.data.business;
        console.log("  ____newBusinesssBox: ", newbusiness);
        newbusiness.push({ name: "", intro: "", showImg: [] });
        this.setData({
            business: newbusiness,
        });
    },

    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function (options) {
        let that = this;
        //调用应用实例的方法获取全局数据
        let userInfo = wx.getStorageSync("userInfo");
        let list = wx.getStorageSync("list");
        let genderList = that.data.genderList;

        console.log("  ___________list: ", list);
        console.log("  ______ userInfo: ", userInfo);

        list = list[0];
        if (!list) {
            // 第一次进来
            that.setData({
                avatarUrl: userInfo.avatarUrl,
                genderList: userInfo.gender === 2 ? [
                    {
                        name: "1", value: "男",
                    }, {
                        name: "2", value: "女", checked: "true",
                    }
                ] : genderList,
                nickName: userInfo.nickName,
            });
        } else {
            // 已经创建了名片
            console.log(" index: common.industryList.indexOf(list.industry");
            console.log(common.industryList.indexOf(list.industry));
            let address = list.address;
            let latitude = wx.getStorageSync("latitude");
            let longitude = wx.getStorageSync("longitude");

            console.log(" ---______ longitude: ", longitude);

            that.setData({
                avatarUrl: list.avatarUrl,
                genderList: list.gender === 2 ? [
                    {
                        name: "1", value: "男",
                    }, {
                        name: "2", value: "女", checked: "true",
                    }
                ] : genderList,
                nickName: list.nickName,
                name: list.name,
                phone: list.phone,
                index: common.industryList.indexOf(list.industry),
                inputNameValue: [
                    list.company,
                    list.position,
                    list.wechat,
                ],
                addressDetail: list.address.detail,
                address: [address.province, address.city, address.area],
                introduce: list.introduce,
                business: list.business,
                latitude: latitude,
                longitude: longitude,
            });
        }




    },

    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function () {

    },

    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function () {
        
    },

    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function () {

    },

    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function () {

    },

    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function () {

    },

    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function () {

    },

    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function () {

    }
});